package com.dx.mes.service.spc.webservice;
/**
 * 服务端(监听MCS->MES消息，并返回消息至MCS01.REPLY)
 */

import com.dx.mes.common.core.base.service.ICIMBaseInterface;
import com.dx.mes.common.core.rabbitmq.BaseConnFactory;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;

@Controller("consumerController")
public class ConsumerController {
	private Logger logger = Logger.getLogger(ConsumerController.class);

	@Resource
	private ApplicationContext context;
	@Resource
	private BaseConnFactory baseConnFactory;

	/**
	 * 初始化创建MQ连接
	 * @throws IOException
	 */
	@PostConstruct
	public void initRpcConsumer() throws IOException{
		//创建连接
		Connection connection = baseConnFactory.creatConnectionFactory().newConnection();

        /**
		 * 在配置档properties文件中找到Qname & service的名字
		 */
		Properties props = new Properties();
		try {
			props.load(ConsumerController.class.getResourceAsStream("/mq.properties"));
		} catch (IOException e) {
//			logger.error("Read mq.properties configuration error");
			e.printStackTrace();
//			logger.error(e.toString());
		}

		/**
		 * 根据properties文件创建consumer连接
		 */
		Iterator<Entry<Object, Object>> it = props.entrySet().iterator();
        while (it.hasNext()) {
            Entry<Object, Object> entry = it.next();
			String mqName = entry.getKey().toString();
			String beanName = entry.getValue().toString();
            try {
                final Channel channel = connection.createChannel();
//				System.out.println(mqName);
				channel.queueDeclare(mqName, true, false, false, null);
                channel.basicQos(1);

//                logger.info("等待接受" + mqName + "消息....");
				//autoAck 为false， rabbitmq会等待消费确认信号再删除
                channel.basicConsume(mqName, false, new DefaultConsumer(channel) {
                	@Override
                	public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {

                        String response = "";
                        try {
                            String inTrx = new String(body,"UTF-8");
//                            logger.info("consumer 接收" + mqName + "的消息是：" + inTrx);

                            String evt_no = GUIDGenerator.javaGUID();
                            ICIMBaseInterface icimBaseinterFace = (ICIMBaseInterface) context.getBean(beanName);
 							response = icimBaseinterFace.subMainProc(evt_no,inTrx);
//                            logger.info("consumer 发送" + mqName + "的消息是：" + response);
							if(StringUtils.isEmpty(response) || response.indexOf(RETURN_CODE_OK) == -1){//失败放入Error Q后续处理
								baseConnFactory.addSAPREQProc(mqName + ".ERR", inTrx);
							}
                        } catch (Exception e) {
//                        	logger.error(Util.stackTraceToString(e));
                        } finally {
                        	//确认消息已被成功接收
                            channel.basicAck(envelope.getDeliveryTag(), false);
                        }
                    }
                });
            } catch (Exception e) {
//            	logger.error(Util.stackTraceToString(e));
            }
        }
    }



}
